<template>
    <div>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>

</el-breadcrumb>

  <el-card class="box-card">

<el-row :gutter="20">
  <el-col :span='8'><el-input placeholder="请输入内容" v-model="querryInfo.query" clearable @clear="getUserList()">
  <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
  </el-input>
</el-col>
  <el-col :span='4'> <el-button type="primary" @click="adddialogVisible=true">添加用户</el-button></el-col>
</el-row>
<!-- //用户列表区 -->
 <el-table
      :data="userlist"
      style="width: 100%"
      border
      stripe>
      <el-table-column type='index'></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
      <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
      <keep-alive>
      <el-table-column prop="mg_state" label="状态" width="180" >
        <template slot-scope="scope">
          <!-- {{scope.row}} -->
          <el-switch v-model="scope.row.mg_state" @change="userstatuechange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      </keep-alive>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <!--修改按钮 -->
             <el-tooltip  class="item" effect="dark" content="编辑" placement="top" :enterable='false'>
          <el-button type="primary" icon="el-icon-edit" @click="editUser(scope.row.id)"></el-button>
             </el-tooltip>
          <!-- 删除按钮 -->
             <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable='false'>
          <el-button type="danger" icon="el-icon-delete" @click="delUser(scope.row.id)"></el-button>
             </el-tooltip>
          <!-- 分配角色按钮 -->
           <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable='false'>
          <el-button type="warning" icon="el-icon-setting"></el-button>
           </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="querryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="querryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
</el-card>
<!-- 添加用户对话框 -->
<el-dialog
  title="添加用户"
  :visible.sync="adddialogVisible"
  width="50%"
  @close="addDialogClosed()"
  >
  <!-- 内容主主体区 -->
  <el-form :model="addFrom" :rules="addFormRules" ref="addFormRef" label-width="100px">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addFrom.username"></el-input>
  </el-form-item>
    <el-form-item label="密码" prop="password">
    <el-input v-model="addFrom.password"></el-input>
  </el-form-item>
    <el-form-item label="邮箱" prop="email">
    <el-input v-model="addFrom.email"></el-input>
  </el-form-item>
    <el-form-item label="手机" prop="mobile">
    <el-input v-model="addFrom.mobile"></el-input>
  </el-form-item>
  </el-form>
  <!-- 底部区域 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="adddialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser()">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改用户区域对话框 -->
<el-dialog
  title="修改用户信息"
  :visible.sync="editdialogVisible"
  width="50%"
  >
  <!-- 对话框主体 -->
  <el-form label-width="80px" :model="editFrom" :rules='editFromRules'>
  <el-form-item label="用户名">
    <el-input disabled v-model="editFrom.username"></el-input>
  </el-form-item>
   <el-form-item label="邮箱" prop='email'>
    <el-input v-model="editFrom.email"></el-input>
  </el-form-item>
   <el-form-item label="手机" prop='mobile'>
    <el-input v-model="editFrom.mobile"></el-input>
  </el-form-item>
  </el-form>

  <!-- 对话框底部 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo()">确 定</el-button>
  </span>
</el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      } else {
        cb(new Error('请输入合法的邮箱'))
      }
    }
    // 验证手机号规则
    var checkMoblie = (rule, value, cb) => {
      const regMoblie = /^1(3|4|5|7|8)\d{9}$/
      if (regMoblie.test(value)) {
        return cb()
      } else {
        cb(new Error('请输入合法的手机号'))
      }
    }
    return {
      querryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userlist: [],
      total: 0,
      // 控制对话框的显示隐藏
      adddialogVisible: false,
      editdialogVisible: false,
      // 添加用户表单数据
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editFrom: {
      },
      // 添加表单的验证对象
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }, {
            min: 3, max: 10, message: '用户名长度在3-10之间', trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }, {
            min: 6, max: 15, message: '密码长度在6-15之间', trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }, {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            min: 11, max: 11, message: '手机号长度在11位', trigger: 'blur'
          }, {
            validator: checkMoblie, trigger: 'blur'
          }
        ]
      },
      editFromRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }, {
            min: 3, max: 10, message: '用户名长度在3-10之间', trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }, {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            min: 11, max: 11, message: '手机号长度在11位', trigger: 'blur'
          }, {
            validator: checkMoblie, trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.querryInfo })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.userlist = res.data.users
      // console.log(this.userlist)
      this.total = res.data.total
    },
    // 监听pagesize 改变的事件
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.querryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.querryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 sweitch 开关状态的改变
    async userstatuechange (userinfo) {
      // console.log(userinfo)
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)// eslint-disable-line no-unused-vars
      // console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户信息失败!')
      }
      this.$message.success('更新状态成功!')
    },
    // 监听表单是否关闭
    addDialogClosed () {
      // 表单的重置
      this.$refs.addFormRef.resetFields()
    },
    // editDialogClosed () {
    //   this.$refs.editFormRef.resetFields()
    // },
    // 添加新用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addFrom)
          console.log(res)
          if (res.meta.status !== 201) {
            return this.$message.error('添加用户失败')
          } else {
            this.$message.success('添加用户成功')
            this.adddialogVisible = false
            this.getUserList()
          }
        } else {
          this.$message.error('请完善信息')
        }
      })
    },
    // 展示编辑用户的对话框
    async editUser (id) {
      const { data: res } = await this.$http.get('users/' + id) // eslint-disable-line no-unused-vars
      this.editdialogVisible = true
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败')
      } else {
        this.editFrom = res.data
        console.log('5')
        console.log(this.editFrom)
      }
    },
    // 修改用户信息提交
    async editUserInfo () {
      const { data: res } = await this.$http.put('users/' + this.editFrom.id,
        {
          email: this.editFromemail, mobile: this.editFrom.mobile
        })
      if (res.meta.status !== 200) {
        return this.$message.error('修改信息失败')
      }
      this.editdialogVisible = false
      this.getUserList()
      this.$message.success('修改用户信息成功')
    },
    // 删除用户
    async delUser (id) {
      const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      } else {
        const { data: res } = await this.$http.delete('users/' + id)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('删除用户信息失败')
        } else {
          this.$message.success('删除用户信息成功')
          this.getUserList()
        }
      }
    }

  }
}
</script>
<style scoped>
  .input-with-select{
    width: 30%;
  }
  .el-pagination{
    margin-top: 15px;
  }
</style>
